﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.SharePoint;

namespace SPRepository
{
    public class MultiUserFieldType : SimpleFieldType<IEnumerable<UserFieldDto>>
    {
        public MultiUserFieldType(Guid id) : base(id)
        {
        }

        private SPFieldUserValueCollection GetSPFieldUserValueCollection(SPListItem item)
        {
            SPWeb web = item.ParentList.ParentWeb;
            return new SPFieldUserValueCollection(web, GetFieldRawValue(item).ToString());
        }

        public override IEnumerable<UserFieldDto> GetValue(SPListItem item)
        {
            SPFieldUserValueCollection fieldValueCollection = GetSPFieldUserValueCollection(item);
            return
                fieldValueCollection.Select(
                    value =>
                    new UserFieldDto(value.LookupId, value.LookupValue, value.SipAddress, value.User.ConvertToDto()))
                                    .ToList();
        }

        public override void SetValue(SPListItem item, IEnumerable<UserFieldDto> values)
        {
            SPFieldUserValueCollection fieldValueCollection = GetSPFieldUserValueCollection(item);
            fieldValueCollection.Clear();
            if (values != null)
            {
                foreach (UserFieldDto value in values)
                {
                    var fieldUserValue = new SPFieldUserValue {LookupId = value.LookupId};
                    fieldValueCollection.Add(fieldUserValue);
                }
            }
            item[FieldId] = fieldValueCollection;
        }
    }
}